<template>
  <!-- 节点弹窗,展示节点相关信息 -->
  <BasicDrawer @register="nodeRegister" title="节点相关信息" width="86%">
    <!--- 设置为几个tab --->
    <a-tabs v-model:activeKey="activeKey" @change="tabChange">
      <a-tab-pane key="1" tab="节点基础信息">
        <a-card size="small">
          <a-space direction="vertical" style="display: block">
            <a-descriptions :column="4" :bordered="true">
              <a-descriptions-item label="节点名称" :span="2"><a>{{vmBasicData.name}}</a></a-descriptions-item>
              <a-descriptions-item label="节点ID" :span="2">{{vmBasicData.id}}</a-descriptions-item>
              <a-descriptions-item label="节点IP" :span="2"><a>{{vmBasicData.ipAddress}}</a></a-descriptions-item>
              <a-descriptions-item label="节点状态" :span="2">
                <a-tag v-if="vmBasicData.statusName == '连接正常'" color="green">
                  <template #icon>
                    <check-circle-outlined />
                  </template>
                  {{ vmBasicData.statusName }}
                </a-tag>
              </a-descriptions-item>
              <a-descriptions-item label="系统名" :span="2">{{vmBasicData.systemName}}</a-descriptions-item>
              <a-descriptions-item label="系统架构" :span="2">{{vmBasicData.systemArc}}</a-descriptions-item>
              <a-descriptions-item label="主机名" :span="2">{{vmBasicData.hostName}}</a-descriptions-item>
              <a-descriptions-item label="CPU数" >{{vmBasicData.cpuCount}}</a-descriptions-item>
              <a-descriptions-item label="GPU数" >{{vmBasicData.gpuCount}}</a-descriptions-item>

              <a-descriptions-item 
              label="内存占用情况" 
              :span="4">
                <Progress 
                status="active"
                :stroke-color="{
                    '0%': '#87d068',
                    '100%': 'red',
                }"
                :percent="vmBasicData.systemRamOcu" 
                size="small" />

              </a-descriptions-item>
              <a-descriptions-item label="虚拟内存占用情况" :span="4">
                <Progress 
                status="active"
                :stroke-color="{
                    '0%': '#87d068',
                    '100%': 'red',
                }"
                :percent="vmBasicData.virtualRamOcu" size="small" />

              </a-descriptions-item>
              <a-descriptions-item label="硬盘占用情况" :span="4">
                <Progress 
                status="active"
                :stroke-color="{
                    '0%': '#87d068',
                    '100%': 'red',
                }"
                :percent="10" 
                size="small" />
              </a-descriptions-item>
            </a-descriptions>
          </a-space>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="2" tab="系统负载">
        <a-card size="small">
          <SingleLine 
          :chartData="cpuDataSource" 
          height="50vh" 
          :option="{ title: { text: 'CPU使用率', left: 'center' } }">
          </SingleLine>
        </a-card>
        <a-card>
          <SingleLine 
          :chartData="ramDataSource" 
          height="50vh" 
          :option="{ title: { text: '内存使用率', left: 'center' } }">
          </SingleLine>
        </a-card>
      </a-tab-pane>

      <a-tab-pane key="3" tab="磁盘负载">
        <a-row :gutter="16">
          <a-col :span="8" v-for="(item, index) in diskInfo" :key="'diskInfo' + index">
            <a-card>
              <Gauge :chartData="item" height="50vh"></Gauge>
              <h1><b>{{item.used}}G/{{item.total}}G</b></h1>
            </a-card>
          </a-col>
        </a-row>
      </a-tab-pane>
      <a-tab-pane key="4" tab="终端">
        <iframe :src="sshUrl" class = "iframediv"></iframe>
      </a-tab-pane>
    </a-tabs>
  </BasicDrawer>
  <div class="p-2">
    
    <!--引用表格-->
    <BasicTable style="border-radius: 5px;" @register="registerTable" class="components-table-demo-nested" :rowSelection="rowSelection">
      <template #tableTitle>
        <a-space :bodyStyle="{ padding: '20px' }">
          <a-input v-model:value="machineName" style="border-radius: 5px;" placeholder="机器名称"/>
          <a-input v-model:value="ipAddress" style="border-radius: 5px;" placeholder="IP地址"/>
          <a-input v-model:value="sysOrgName" style="border-radius: 5px;" placeholder="分组"/>
          <a-button type="primary" shape="round" @click="handleSearch">搜索</a-button>
          <a-button type="danger" shape="round" @click="handleAdd">添加机器</a-button>
        </a-space>
        <a-dropdown v-if="selectedRowKeys.length > 0">
          <template #overlay>
            <a-menu>
              <a-menu-item key="1" @click="batchHandleDelete">
                <Icon icon="ant-design:delete-outlined"></Icon>
                删除
              </a-menu-item>
            </a-menu>
          </template>
          <a-button>批量操作
            <Icon icon="mdi:chevron-down"></Icon>
          </a-button>
        </a-dropdown>
      </template>
      <!--- 自定义列 --->
      <template #bodyCell="{ column, record}">
        <a v-if="column.dataIndex == 'name'">
          {{ record.name }}
        </a>
        <a-tag v-if="column.dataIndex == 'statusName' && record.status == 3" color="green">
          <template #icon>
            <check-circle-outlined />
          </template>
          {{ record.statusName }}
        </a-tag>
        <a-tag v-else-if="column.dataIndex == 'statusName' && (record.status == 4 || record.status == 2)" color="red">
          {{ record.statusName }}
        </a-tag>
        <a-tag v-else-if="column.dataIndex == 'statusName' && (record.status == 5 || record.status == 1) " color="yellow">
          <template #icon>
            <clock-circle-outlined />
          </template>
          {{record.statusName}}
        </a-tag>
      </template>
      <template #expandedRowRender="{ record }">
        <a-table :columns="innerColumns" :data-source="record.containerData" :pagination="false">
          <template #bodyCell="{ column,record }">
            <a v-if = "column.dataIndex == 'containerStatus' ">
            <a-badge v-if="record.containerStatusType == 'waiting' " status="processing" color="yellow" :text="record.containerStatusName"/>
            <a-badge v-else-if="record.containerStatusType == 'normal' " status="processing" color="green" :text="record.containerStatusName"/>
            <a-badge v-else-if="record.containerStatusType == 'error' " status="processing" color="red" :text="record.containerStatusName"/>
          </a>
          </template>
        </a-table>
      </template>
      <!--操作栏-->
      <template #action="{ record }">
        <!--- 改成用几个醒目的按钮 --->
        <a-space v-if="record.status == 3">
          <a-button style="border-radius: 5px;" size="small" type="primary" @click="handleEdit(record)">编辑</a-button>
          <a-button style="border-radius: 5px;" size="small" type="primary" @click="handleDetail(record)">详情</a-button>
          <a-button style="border-radius: 5px;" size="small" type="danger" @click="handleDelete(record)">删除</a-button>
        </a-space>
        <a-space v-else-if="record.status==5">
          <a-button style="border-radius: 5px;" size="small" type="danger" @click="handleDetail(record)">安装</a-button>
          <a-button style="border-radius: 5px;" size="small" type="primary" @click="handleEdit(record)">编辑</a-button>
          <a-button style="border-radius: 5px;" size="small" type="danger" @click="handleDelete(record)">删除</a-button>
        </a-space>
      </template>
    </BasicTable>
    <!-- 表单区域 -->
    <VmNodeModal ref="registerModal" @success="handleSuccess"></VmNodeModal>
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable } from '/@/components/Table';
  import { ref } from 'vue';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { queryDiskInfoById,queryRamLoadDataById,queryCpuLoadDataById,queryLoadDataById,list, deleteOne, batchDelete, getImportUrl, getExportUrl } from './VmNode.api';
  import { columns } from './VmNode.data';
  import { innerColumns } from './VmContainer.data';
  import VmNodeModal from './components/VmNodeModal.vue';
  import { BasicDrawer, useDrawer } from '/@/components/Drawer';
  import {CheckCircleOutlined,ClockCircleOutlined} from '@ant-design/icons-vue';
  import { Progress } from 'ant-design-vue';
  import SingleLine from '/@/components/chart/SingleLine.vue';
  import Gauge from '/@/components/chart/Gauge.vue';

  const sshUrl = ref<string>('');

  const ramDataSource: any[] = [];
  const cpuDataSource: any[] = [];
  const diskInfo = ref<any>([]);

  function handleSearch() {
    queryParam['name'] = machineName.value;
    queryParam['nodeIpAddress'] = ipAddress.value;
    queryParam['sysOrgName'] = sysOrgName.value;
    reload();
  }

  const machineName = ref<string>('');
  const ipAddress = ref<string>('');
  const sysOrgName = ref<string>('');

  function getData(id) {
    queryRamLoadDataById(id).then((data) => {
      console.log(data);
      for (let i = 0; i < data.result.length; i++) {
        let obj = { name: '', value: 0 };
        obj.name = data.result[i].name
        obj.value = data.result[i].value;
        ramDataSource.push(obj)
      }
    }).catch((err) => {
      console.log(err);
    })
    queryCpuLoadDataById(id).then((data) => {
      console.log(data);
      for (let i = 0; i < data.result.length; i++) {
        let obj = { name: '', value: 0 };
        obj.name = data.result[i].name
        obj.value = data.result[i].value;
        cpuDataSource.push(obj)
      }
    }).catch((err) => {
      console.log(err);
    })
    queryDiskInfoById(id).then((data) => {
      console.log("data",data);
      diskInfo.value = data.result;
    }).catch((err) => {
      console.log(err);
    })

  }

  const activeKey = ref<Number>();
  function tabChange() {
    
  }

  const [nodeRegister, nodeDrawerMethods] = useDrawer();
  const vmNodeData = ref<any>();

  const registerModal = ref();

  const queryParam = ref<any>();
  //BasicTable绑定注册
  const {  tableContext } = useListPage({
    tableProps: {
      title: '节点列表',
      api: list,
      columns,
      canResize:true,
      useSearchForm: false,
      actionColumn: {
        width: 200,
        resizable: true,
      },
      beforeFetch: (params) => {
        return Object.assign(params, queryParam);
      },
    },
    exportConfig: {
      name: "vm_image",
      url: getExportUrl,
      params: queryParam,
    },
	  importConfig: {
	    url: getImportUrl,
	    success: handleSuccess
	  },
  });
  const [registerTable, { reload }, { rowSelection, selectedRowKeys }] = tableContext;


  /**
   * 新增事件
   */
  function handleAdd() {
    registerModal.value.disableSubmit = false;
    registerModal.value.add();
  }
  
  /**
   * 编辑事件
   */
  function handleEdit(record: Recordable) {
    registerModal.value.disableSubmit = false;
    registerModal.value.edit(record);
  }
  const vmBasicData = ref();
  /**
   * 详情
   */
  function handleDetail(record: Recordable) {
    // 设置为弹窗
    console.log("打开了弹窗",record);
    vmNodeData.value = record;
    // 查询数据
    queryLoadDataById(record.nodeId).then((data) => {
      console.log(data)
      vmBasicData.value = data.result;
      getData(record.nodeId);
      const webSSHServiceUrl = "http://120.24.170.16:8888/?";
      console.log("获取得到的record为:",record)
      sshUrl.value = webSSHServiceUrl + "hostname=" + record.nodeIpAddress    + "&" + 
                                      "username=" + record.username + "&" +
                                      "password=" + record.passwordBase64 + "&" +
                                      "port="     + 22     ;
      nodeDrawerMethods.openDrawer(true,record);
    }).catch((err) => {
      console.log(err)
    })
    
  }
   

  /**
   * 删除事件
   */
  async function handleDelete(record) {
    await deleteOne({ id: record.id }, handleSuccess);
  }
   
  /**
   * 批量删除事件
   */
  async function batchHandleDelete() {
    await batchDelete({ ids: selectedRowKeys.value }, handleSuccess);
  }
   
  /**
   * 成功回调
   */
  function handleSuccess() {
    (selectedRowKeys.value = []) && reload();
  }
   
</script>


<style lang="less" scoped>
  .jeecg-basic-table-form-container {
    padding: 0;
    .table-page-search-submitButtons {
      display: block;
      margin-bottom: 24px;
      white-space: nowrap;
    }
    .query-group-cust{
      width: calc(50% - 15px);
      min-width: 100px !important;
    }
    .query-group-split-cust{
      width: 30px;
      display: inline-block;
      text-align: center
    }
  }
  .iframediv {
    width: 100%;
    height: 500px;
    margin: 10px auto;
    overflow: hidden;
  }
</style>


